import axios from 'axios';
import { message } from 'antd';
import { getToken } from '../utils/userToken';

const instance = axios.create({
  timeout: 10 * 1000,
});

instance.interceptors.request.use(
  (config) => {
    config.headers['Authorization'] = `Bearer ${getToken()}`;
    return config;
  },
  (error) => Promise.reject(error)
);

instance.interceptors.response.use((res) => {
  const resData = (res.data || {}) as RESType;
  const { code, data, msg } = resData;
  if (code !== 200) {
    if (msg) {
      message.error(msg);
    }
    throw new Error(msg);
  }

  return data as any;
});

export default instance;

export type RESType = {
  code: number;
  data?: RESDataType;
  msg?: string;
};

export type RESDataType = {
  [key: string]: any;
};
